package org.jasig.cas.client.authentication.sdk;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author CreGu
 *
 */
public class SdkUtil {
	protected static final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(SdkUtil.class);

	static private final String DEFAULT_CHARSET = "utf-8";

	public static String getDefaultCharset() {
		return DEFAULT_CHARSET;
	}

	public static String construcUrl(String casServerUrlPrefix,
			String urlSuffix, Map<String, String> urlParameters) {
		final String suffix = urlSuffix;
		final StringBuilder buffer = new StringBuilder(urlParameters.size()
				* 10 + casServerUrlPrefix.length() + suffix.length() + 1);

		int i = 0;

		buffer.append(casServerUrlPrefix);
		if (!casServerUrlPrefix.endsWith("/")) {
			buffer.append("/");
		}
		buffer.append(suffix);

		for (Map.Entry<String, String> entry : urlParameters.entrySet()) {
			final String key = entry.getKey();
			final String value = entry.getValue();

			if (value != null) {
				buffer.append(i++ == 0 ? "?" : "&");
				buffer.append(key);
				buffer.append("=");
				final String encodedValue = encodeUrl(value);
				buffer.append(encodedValue);
			}
		}

		return buffer.toString();
	}

	/**
	 * Encodes a URL using the URLEncoder format.
	 *
	 * @param url
	 *            the url to encode.
	 * @return the encoded url, or the original url if "UTF-8" character
	 *         encoding could not be found.
	 */
	protected final static String encodeUrl(final String url) {
		if (url == null) {
			return null;
		}

		try {
			return URLEncoder.encode(url, "UTF-8");
		} catch (final UnsupportedEncodingException e) {
			return url;
		}
	}
}
